package com.mytrans.transaction;

import com.mytrans.beans.TranceRecordBean;
import com.mytrans.client.ListenerServlet;
import com.mytrans.util.JsonType;
import com.mytrans.util.ServletUtil;
import com.zhou.util.JsonUtil;

import javax.servlet.http.HttpServlet;

public class DefaultTransactionListener implements TransactionListener {

    private ExecutorContainer executorContainer;

    public DefaultTransactionListener(ExecutorContainer executorContainer){
        this.executorContainer = executorContainer;
    }

    @Override
    public <T> void commitListener(TranceRecordBean bean) throws Exception {
        TransactionExecutor<T> executor = executorContainer.getExecutor(bean.getExecutorKey());
        JsonType jsonType = executor.getParamType();
        T param = JsonUtil.getGson().fromJson(bean.getData(), jsonType.getType());
        executor.commit(param);
    }

    @Override
    public <T> void rollBackListener(TranceRecordBean bean) throws Exception {
        TransactionExecutor<T> executor = executorContainer.getExecutor(bean.getExecutorKey());
        JsonType jsonType = executor.getParamType();
        T param = JsonUtil.getGson().fromJson(bean.getData(), jsonType.getType());
        executor.commit(param);
    }

    @Override
    public HttpServlet getServlet(){
        return new ListenerServlet(this);
    }
}
